package com.dk.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUploadException;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.dk.cache.Cache;
import com.dk.cache.memory.MemoryCacheManager;
import com.dk.entity.ApplyInfo;
import com.dk.entity.ApplyInfoExample;
import com.dk.entity.PersonalInfo;
import com.dk.entity.PersonalInfoExample;
import com.dk.mapping.ApplyInfoMapper;
import com.dk.mapping.PersonalInfoMapper;
import com.dk.util.VerifyCodeUtils;
import com.dk.util.sms.MessageXsend;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.io.IORuntimeException;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;

@Controller
@RequestMapping("/")
public class HelloController {
	@Autowired
	ApplyInfoMapper applyInfoMapper;
	@Autowired
	PersonalInfoMapper personalInfoMapper;
	
	@Autowired
	DbSearcher _searcher;
	
	Cache codeCache=MemoryCacheManager.getMemoryCache("code");
	
	@Value("${imageDir}")
	private String imageDir;
	
	@RequestMapping("index.do")
	@ResponseBody
	public String index(Model model,HttpServletRequest request,HttpServletResponse response) {
		return "hello";
	}
	
	@RequestMapping("userImage/{filePath}/i.do")
	@ResponseBody
	public void userImage(@PathVariable("filePath") String filePath,HttpServletRequest request,HttpServletResponse response) throws IOException {
		File f=new File(imageDir,filePath);
		if(f.isFile()){
			response.setContentType("image/jpeg");
			response.setDateHeader("expries", -1);
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			//10.将图片写给浏览器
			// 创建文件输入流
			FileInputStream is = new FileInputStream(f);
			// 响应输出流
			ServletOutputStream out = response.getOutputStream();
			// 创建缓冲区
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			is.close();
			out.flush();
			out.close();
		}
	}

	@RequestMapping("examine.do")
	public String examine(Model model,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		String id = request.getParameter("id");
		String stat = request.getParameter("stat");
		ApplyInfo applyInfo=new ApplyInfo();
		applyInfo.setId(id);
		applyInfo.setApplyStat(Integer.parseInt(stat));
		applyInfo.setExamineTime(System.currentTimeMillis()+"");
		
		ApplyInfoExample example=new ApplyInfoExample();
		example.createCriteria().andIdEqualTo(id);
		applyInfoMapper.updateByExampleSelective(applyInfo, example);
		
		return "redirect:/admin.html?message="+URLEncoder.encode(URLEncoder.encode("审核完成","UTF-8"),"UTF-8");
	}
	public static int pageSize=4;
	@RequestMapping("tmp.do")
	public String admin(Model model,HttpServletRequest request,HttpServletResponse response) {
		String name=request.getParameter("name");
		String id=request.getParameter("id");
		String search=request.getParameter("search");
		String stat=request.getParameter("stat");
		
		String page=request.getParameter("page");
		model.addAttribute("list", applyInfoMapper.selectByAdmin(
				StrUtil.format("%{}%", name)
				, StrUtil.format("%{}%", id)
				, StrUtil.format("%{}%", search)
				, StrUtil.isBlank(stat) ? null : stat
				,(Integer.parseInt(page)-1)*pageSize
				,pageSize));
		return "tmp";
	}

	@RequestMapping("userList.do")
	public String userList(Model model,HttpServletRequest request,HttpServletResponse response) {
		String name=request.getParameter("name");
		String id=request.getParameter("id");
		String search=request.getParameter("search");
		String type=request.getParameter("type");
		
		String page=request.getParameter("page");
		
		PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(page)*1);
		model.addAttribute("list", personalInfoMapper.selectByUserList(
				StrUtil.format("%{}%", name)
				, StrUtil.format("%{}%", id)
				, StrUtil.format("%{}%", search)
				, StrUtil.isBlank(type) ? null : type
				,(Integer.parseInt(page)-1)*pageSize
				,pageSize));
		return "userList";
	}

	@RequestMapping("addCheck.do")
	public String addCheck(
			HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		/*if(!request.getParameter("cod").equals(request.getSession().getAttribute("verCode"))){
			return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("验证码错误","UTF-8"),"UTF-8");
		}*/

		if(!VerificationCode(request.getParameter("wxid"), request.getParameter("smscod"))){
			return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("短信验证码错误","UTF-8"),"UTF-8");
		}
		
		PersonalInfo personalInfo=new PersonalInfo();
		personalInfo.setUserId(request.getParameter("wxid"));
		personalInfo.setUserName(request.getParameter("name"));
		personalInfo.setPhonenum(request.getParameter("phonenum"));
		personalInfo.setZfb(request.getParameter("QQ"));
		personalInfo.setLendingPlatform(request.getParameter("ptname"));
		personalInfo.setLendingNumber(new Double(request.getParameter("ptmoney")));
		personalInfo.setLendingCondition(request.getParameter("pttiaojian"));
		personalInfo.setType(3);
		
		PersonalInfoExample example=new PersonalInfoExample();
		example.createCriteria().andUserIdEqualTo(personalInfo.getUserId());
		
		if(personalInfoMapper.selectByExample(example).size() == 0){
			personalInfoMapper.insertSelective(personalInfo);	
		}else{
			personalInfoMapper.updateByExampleSelective(personalInfo,example);
		}
		
		return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("申请成功","UTF-8"),"UTF-8");
	}
	@RequestMapping("sendSmsCode.do")
	@ResponseBody
	public String sendSmsCode(HttpServletRequest request,HttpServletResponse response){
		/*if(!request.getParameter("cod").equals(request.getSession().getAttribute("verCode"))){
			JSONObject object=new JSONObject();
			object.put("ok", "0");
			object.put("message", "请输入正确的验证码");
			return object.toJSONString();
		}*/
		String wxid=request.getParameter("wxid");
		String code = (String) codeCache.get(wxid);
		String phonenum=request.getParameter("phonenum");
		if(code == null){
			code=RandomUtil.randomInt(100000, 1000000)+"";
			codeCache.put(wxid, code);
			System.out.println("smscode:"+code);
			MessageXsend.sendSmsCode(phonenum, code);
		}

		JSONObject object=new JSONObject();
		object.put("ok", "1");
		object.put("message", "验证码已发送");
		return object.toJSONString();
	}
	
	public boolean VerificationCode(String wxid,String code){
		String sysCode = (String) codeCache.get(wxid);
		codeCache.remove(wxid);
		if(code.equals(sysCode)){
			return true;
		}else{
			return false;
		}
	}
	
	@RequestMapping("addReq.do")
	public String addReq(
			HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		/*if(!request.getParameter("cod").equals(request.getSession().getAttribute("verCode"))){
			return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("验证码错误","UTF-8"),"UTF-8");
		}*/

		if(!VerificationCode(request.getParameter("wxid"), request.getParameter("smscod"))){
			return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("短信验证码错误","UTF-8"),"UTF-8");
		}
		
		PersonalInfo personalInfo=new PersonalInfo();
		personalInfo.setUserId(request.getParameter("wxid"));
		personalInfo.setUserName(request.getParameter("name"));
		personalInfo.setPhonenum(request.getParameter("phonenum"));
		personalInfo.setZfb(request.getParameter("zfb"));
		personalInfo.setType(2);
		
		PersonalInfoExample example=new PersonalInfoExample();
		example.createCriteria().andUserIdEqualTo(personalInfo.getUserId());
		
		if(personalInfoMapper.selectByExample(example).size() == 0){
			personalInfoMapper.insertSelective(personalInfo);	
		}else{
			personalInfoMapper.updateByExampleSelective(personalInfo,example);
		}
		
		return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("申请成功，可使用您的手机号作为推荐号。","UTF-8"),"UTF-8");
	}
	@RequestMapping("addApply.do")
	public String addApply(
			@RequestParam(value="sfz_1",required=false) MultipartFile sfz_1,
			@RequestParam(value="sfz_2",required=false) MultipartFile sfz_2,
//			@RequestParam(value="sfz_3",required=false) MultipartFile sfz_3,
			HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IORuntimeException, IOException{
		
		/*if(!request.getParameter("cod").equals(request.getSession().getAttribute("verCode"))){
			return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("验证码错误","UTF-8"),"UTF-8");
		}*/
		
		if(!VerificationCode(request.getParameter("wxid"), request.getParameter("smscod"))){
			return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("短信验证码错误","UTF-8"),"UTF-8");
		}	
		
		
		PersonalInfo personalInfo=new PersonalInfo();
		personalInfo.setUserId(request.getParameter("wxid"));
		personalInfo.setSfz(request.getParameter("sfz"));
		personalInfo.setIp(request.getRemoteAddr());
		DataBlock fdata = _searcher.binarySearch(personalInfo.getIp());
		personalInfo.setIpToAddress(fdata.toString());
		personalInfo.setGps(request.getParameter("gps"));
		personalInfo.setUserName(request.getParameter("name"));
		personalInfo.setDizhic(request.getParameter("dizhic"));
		personalInfo.setQq(request.getParameter("QQ"));
		personalInfo.setWx(request.getParameter("wx"));
		personalInfo.setZfb(request.getParameter("zfb"));
		if(request.getParameter("zmf") != null){
			personalInfo.setZmf(Integer.parseInt(request.getParameter("zmf")));	
		}
		if(request.getParameter("hbjb") != null){
			personalInfo.setHb(Integer.parseInt(request.getParameter("hbjb")));
		}
		if(request.getParameter("hbjb") != null){
			personalInfo.setJb(Integer.parseInt(request.getParameter("hbjb")));
		}
		personalInfo.setSlsf(request.getParameter("slsf"));
		if(request.getParameter("zfuz") != null){
			personalInfo.setZfuz(new Double(request.getParameter("zfuz")));
		}
		if(request.getParameter("zhuank") != null){
			personalInfo.setZhuank(new Double(request.getParameter("zhuank")));
		}
		if(request.getParameter("slyq") != null){
			personalInfo.setSlyq(Integer.parseInt(request.getParameter("slyq")));
		}
		if(request.getParameter("sljl") != null){
			personalInfo.setSljl(Integer.parseInt(request.getParameter("sljl")));
		}
		personalInfo.setPhonenum(request.getParameter("phonenum"));
		personalInfo.setPhonepassword(request.getParameter("phonePassword"));
		personalInfo.setTjr(request.getParameter("tjr"));
		personalInfo.setType(1);

		if(sfz_1 != null){
			File sfz1=new File(imageDir,StrUtil.format("{}_1.{}", request.getParameter("sfz"),FileUtil.extName(sfz_1.getOriginalFilename())));
			FileUtil.writeBytes(sfz_1.getBytes(), sfz1);	
			personalInfo.setImage1(sfz1.getName());
		}
		if(sfz_2 != null){
			File sfz2=new File(imageDir,StrUtil.format("{}_2.{}", request.getParameter("sfz"),FileUtil.extName(sfz_1.getOriginalFilename())));
			FileUtil.writeBytes(sfz_2.getBytes(), sfz2);	
			personalInfo.setImage2(sfz2.getName());
		}

//		File sfz3=new File(imageDir,StrUtil.format("{}_3.{}", request.getParameter("sfz"),FileUtil.extName(sfz_1.getOriginalFilename())));
//		FileUtil.writeBytes(sfz_3.getBytes(), sfz3);
//		personalInfo.setImage3(sfz3.getName());
		PersonalInfoExample example=new PersonalInfoExample();
		example.createCriteria().andUserIdEqualTo(personalInfo.getUserId());
		
		if(personalInfoMapper.selectByExample(example).size() == 0){
			personalInfoMapper.insertSelective(personalInfo);	
		}else{
			personalInfoMapper.updateByExampleSelective(personalInfo,example);
		}
		
		
		ApplyInfo applyInfo=new ApplyInfo();
		applyInfo.setId(UUID.randomUUID().toString());
		applyInfo.setUserId(personalInfo.getUserId());
		applyInfo.setApplyType(Integer.parseInt(request.getParameter("applyType")));
		applyInfo.setApplyStat(1);
		applyInfo.setApplyTime(System.currentTimeMillis()+"");
		
		applyInfoMapper.insertSelective(applyInfo);
		
		return "redirect:/index.html?message="+URLEncoder.encode(URLEncoder.encode("申请成功","UTF-8"),"UTF-8");
	}

	@RequestMapping("getCode.do")
	@ResponseBody
	public String getCode(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException{
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 
		HttpSession session = request.getSession(true); 
		session.removeAttribute("verCode");
        session.setAttribute("verCode", verifyCode.toLowerCase()); 
        int w = 100, h = 30; 
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); 
		return null;
	}
}
